﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Core.Library;
using DataObject.Members;
using DataObject.Ref;

namespace Event
{
    public partial class dologin : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentType = "text/html";

            string SECURE_AUTH_KEY = "JYVa8M4QAleGIrv|F<+17HL4Cn`<@9c?lw#)En<SPD),$2?j-rngq&wP-k1<V`;2";

            string username = "";
            if (Request.QueryString["username"] != null && Request.QueryString["username"] != String.Empty)
            {

                username = Request.QueryString["username"].ToString().Trim();
            }
            string email = "";
            if (Request.QueryString["email"] != null && Request.QueryString["email"] != String.Empty)
            {
                email = Request.QueryString["email"].ToString().Trim();
            }
            string full_name = "";
            if (Request.QueryString["full_name"] != null && Request.QueryString["full_name"] != String.Empty)
            {
                full_name = Request.QueryString["full_name"].ToString().Trim();
            }

            string status = "-1";
            if (Request.QueryString["status"] != null && Request.QueryString["status"] != String.Empty)
            {
                status = Request.QueryString["status"].ToString().Trim();
            }

            string round = "-1";
            if (Request.QueryString["round"] != null && Request.QueryString["round"] != String.Empty)
            {
                round = Request.QueryString["round"].ToString().Trim();
            }
            string type = "0";
            if (Request.QueryString["type"] != null && Request.QueryString["type"] != String.Empty)
            {
                type = Request.QueryString["type"].ToString().Trim();
            }

            string checksum = "";
            if (Request.QueryString["checksum"] != null && Request.QueryString["checksum"] != String.Empty)
            {
                checksum = Request.QueryString["checksum"].ToString().Trim();
            }

            string avatar = String.Empty;
            if (Request.QueryString["avatar"] != null && Request.QueryString["avatar"] != String.Empty)
            {
                avatar = Request.QueryString["avatar"].ToString().Trim();
            }

            string id = "";
            if (Request.QueryString["id"] != null && Request.QueryString["id"] != String.Empty)
            {
                id = Request.QueryString["id"].ToString().Trim();
            }


            string memberId = "";
            if (Request.QueryString["memberId"] != null && Request.QueryString["memberId"] != String.Empty)
            {
                id = Request.QueryString["memberId"].ToString().Trim();
            }

            if (type == "1")
            {
                FormsAuthentication.SignOut();
                Response.Write("1"); ;
            }

            string md5_check = MD5(id + username + email + SECURE_AUTH_KEY);
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(email))
            {
                if (md5_check == checksum || type == "2")
                {
                    if (HttpContext.Current.Request.IsAuthenticated)
                    {
                        FormsIdentity ident = HttpContext.Current.User.Identity as FormsIdentity;
                        if (ident != null)
                        {
                            try
                            {
                                FormsAuthenticationTicket ticket1 = ident.Ticket;
                                string[] userData = ticket1.UserData.Split('|');
                                string UName = userData[0];
                                string Email = userData[1];
                                string Status = userData[3];
                                string ULink = "";
                                string UDisplay = "";
                                string UClick = "";
                                string UrlRound = "#";
                                MembersObject u = MembersCache.Members_GetByEmail(Email);
                                if (u != null)
                                {
                                    if (u.Member_Status == (int)MemberStatus.IsPublished && RefCache.Ref_GetLockEditStatus() && u.Member_InRound >= RefCache.Ref_GetCurrentRound())
                                    {
                                        UDisplay = "Sửa thông tin";
                                        ULink = "/sua-thong-tin.htm";
                                        // chua dc set vong thi UrlRound ve vong 1
                                    }
                                    else if (u.Member_Status == (int)MemberStatus.IsNoRegister && RefCache.Ref_GetLockRegisterStatus())
                                    {
                                        UDisplay = "Đăng ký dự thi";
                                        ULink = "/dang-ky-du-thi.htm";
                                    }
                                    if (u.Member_Status == (int)MemberStatus.IsPublished)
                                    {
                                        if (u.Member_InRound == (int)MemberRound.NoRound)
                                            u.Member_InRound = (int) MemberRound.Round1;
                                        UrlRound = UrlHelpers.MembersDetails(u.Member_ID,u.Member_Email, u.Member_InRound);
                                    }
                                    //if (u.Member_Status == (int)MemberStatus.IsNoRegister && string.IsNullOrWhiteSpace(u.Member_Avatar) && !string.IsNullOrWhiteSpace(avatar))
                                    //{
                                    //    u.Member_Avatar = avatar;
                                    //    MembersController.Members_UpdateFrontEnd(u);
                                    //}

                                }
                                else
                                {
                                    u = new MembersObject();
                                    u.Member_Name = UName;
                                    u.Member_Email = Email;
                                    u.Member_Status = (int)MemberStatus.IsNoRegister;
                                    u.Member_InRound = (int)MemberRound.NoRound;
                                    u.Member_Birthday = DateTime.Now;
                                    u.Member_RegisterDate = DateTime.Now;
                                    MembersController.Members_Insert(u);
                                }
                                if (UName != username)
                                {
                                    string userDataString = username + "|" + email + "|" + full_name + "|" + status;
                                    HttpCookie authCookie = FormsAuthentication.GetAuthCookie(username, true);
                                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
                                    FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, DateTime.Now, DateTime.Now.AddMonths(1), ticket.IsPersistent, userDataString);
                                    authCookie.Value = FormsAuthentication.Encrypt(newTicket);
                                    Response.Cookies.Add(authCookie);


                                    // luu vao session
                                    HttpContext.Current.Session[Const.AuthenticationSessionName] = userDataString;
                                    // luu vao session

                                    Response.Write("VietID.bindData({'UName':'" + username + "','UEmail':'" + email + "','ULink':'" + ULink + "' ,'UDisplay':'" + UDisplay + "','UClick':'" + UClick + "','UrlRound':'" + UrlRound + "'})");
                                }
                                else
                                {

                                    Response.Write("VietID.bindData({'UName':'" + UName + "','UEmail':'" + Email + "','ULink':'" + ULink + "' ,'UDisplay':'" + UDisplay + "','UClick':'" + UClick + "','UrlRound':'" + UrlRound + "'})");
                                }
                            }
                            catch (Exception ex)
                            {
                                Response.Write(ex.Message);
                            }
                        }
                    }
                    else if (HttpContext.Current.Session[Const.AuthenticationSessionName] != null)
                    {
                        string[] userData = HttpContext.Current.Session[Const.AuthenticationSessionName].ToString().Split('|');
                        string UName = userData[0];
                        string Email = userData[1];
                        string Status = userData[3];
                        string ULink = "";
                        string UDisplay = "";
                        string UClick = "";
                        string UrlRound = "#";
                        MembersObject u = MembersCache.Members_GetByEmail(Email);
                        if (u != null)
                        {
                            if (u.Member_Status == (int)MemberStatus.IsPublished && RefCache.Ref_GetLockEditStatus() && u.Member_InRound >= RefCache.Ref_GetCurrentRound())
                            {
                                UDisplay = "Sửa thông tin";
                                ULink = "/sua-thong-tin.htm";
                                // chua dc set vong thi UrlRound ve vong 1
                            }
                            else if (u.Member_Status == (int)MemberStatus.IsNoRegister && RefCache.Ref_GetLockRegisterStatus())
                            {
                                UDisplay = "Đăng ký dự thi";
                                ULink = "/dang-ky-du-thi.htm";
                            }
                            if (u.Member_Status == (int)MemberStatus.IsPublished)
                            {
                                if (u.Member_InRound == (int)MemberRound.NoRound)
                                    u.Member_InRound = (int)MemberRound.Round1;
                                UrlRound = UrlHelpers.MembersDetails(u.Member_ID, u.Member_Email, u.Member_InRound);
                            }
                            //if (u.Member_Status == (int)MemberStatus.IsNoRegister && string.IsNullOrWhiteSpace(u.Member_Avatar) && !string.IsNullOrWhiteSpace(avatar))
                            //{
                            //    u.Member_Avatar = avatar;
                            //    MembersController.Members_UpdateFrontEnd(u);
                            //}

                        }
                        else
                        {
                            u = new MembersObject();
                            u.Member_Name = UName;
                            u.Member_Email = Email;
                            u.Member_Status = (int)MemberStatus.IsNoRegister;
                            u.Member_InRound = (int)MemberRound.NoRound;
                            u.Member_Birthday = DateTime.Now;
                            u.Member_RegisterDate = DateTime.Now;
                            MembersController.Members_Insert(u);
                        }
                        if (UName != username)
                        {
                            string userDataString = username + "|" + email + "|" + full_name + "|" + status;
                            HttpCookie authCookie = FormsAuthentication.GetAuthCookie(username, true);
                            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
                            FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, DateTime.Now, DateTime.Now.AddMonths(1), ticket.IsPersistent, userDataString);
                            authCookie.Value = FormsAuthentication.Encrypt(newTicket);
                            Response.Cookies.Add(authCookie);


                            // luu vao session
                            HttpContext.Current.Session[Const.AuthenticationSessionName] = userDataString;
                            // luu vao session

                            Response.Write("VietID.bindData({'UName':'" + username + "','UEmail':'" + email + "','ULink':'" + ULink + "' ,'UDisplay':'" + UDisplay + "','UClick':'" + UClick + "','UrlRound':'" + UrlRound + "'})");
                        }
                        else
                        {

                            Response.Write("VietID.bindData({'UName':'" + UName + "','UEmail':'" + Email + "','ULink':'" + ULink + "' ,'UDisplay':'" + UDisplay + "','UClick':'" + UClick + "','UrlRound':'" + UrlRound + "'})");
                        }
                    }
                    else
                    {

                        var UDisplay = string.Empty;
                        var ULink = string.Empty;
                        string UClick = string.Empty;
                        string UrlRound = "#";
                        string UserName = string.Empty;
                        MembersObject u = MembersCache.Members_GetByEmail(email);
                        if (u != null)
                        {
                            if (u.Member_Status == (int)MemberStatus.IsPublished && RefCache.Ref_GetLockEditStatus() && u.Member_InRound >= RefCache.Ref_GetCurrentRound())
                            {
                                UDisplay = "Sửa thông tin";
                                ULink = "/sua-thong-tin.htm";
                                // chua dc set vong thi UrlRound ve vong 1
                            }
                            else if (u.Member_Status == (int)MemberStatus.IsNoRegister && RefCache.Ref_GetLockRegisterStatus())
                            {
                                UDisplay = "Đăng ký dự thi";
                                ULink = "/dang-ky-du-thi.htm";
                            }
                            if (u.Member_Status == (int)MemberStatus.IsPublished)
                            {
                                if (u.Member_InRound == (int)MemberRound.NoRound)
                                    u.Member_InRound = (int)MemberRound.Round1;
                                UrlRound = UrlHelpers.MembersDetails(u.Member_ID, u.Member_Email, u.Member_InRound);
                                UserName = username;
                            } 
                        }

                        string userDataString = username + "|" + email + "|" + full_name + "|" + status;
                        HttpCookie authCookie = FormsAuthentication.GetAuthCookie(username, true);
                        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
                        FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, DateTime.Now, DateTime.Now.AddMonths(1), ticket.IsPersistent, userDataString);
                        authCookie.Value = FormsAuthentication.Encrypt(newTicket);
                        Response.Cookies.Add(authCookie);

                        // luu vao session
                        HttpContext.Current.Session[Const.AuthenticationSessionName] = userDataString;
                        // luu vao session

                        //Response.Write("VietID.bindData({'UName':'" + username + "','UEmail':'" + email + "' })");
                        Response.Write("VietID.bindData({'UName':'" + UserName + "','UEmail':'" + email + "','ULink':'" + ULink + "' ,'UDisplay':'" + UDisplay + "','UClick':'" + UClick + "','UrlRound':'" + UrlRound + "'})");
                    }
                }
            }
            else
            {
                FormsAuthentication.SignOut();

                // xoa session
                HttpContext.Current.Session.Remove(Const.AuthenticationSessionName);
                // xoa session

                //CacheController.Remove(Constants.PARENT_CATEGORY_FOR_PHOTO_LIKE, username);

                //Response.Write("VietID.bindData('null')");
            }

        }

        public static string MD5(string password)
        {
            byte[] textBytes = System.Text.Encoding.Default.GetBytes(password);
            try
            {
                System.Security.Cryptography.MD5CryptoServiceProvider cryptHandler;
                cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] hash = cryptHandler.ComputeHash(textBytes);
                string ret = "";
                foreach (byte a in hash)
                {
                    if (a < 16)
                        ret += "0" + a.ToString("x");
                    else
                        ret += a.ToString("x");
                }
                return ret;
            }
            catch
            {
                throw;
            }
        }
    }
}